package com.health.ts.config;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import lombok.extern.slf4j.Slf4j;

/**
 * 调用链跟踪aop
 */
@Slf4j
@Aspect
@Configuration
public class TraceAspect {

    // 定义切点Pointcut
    @Pointcut("execution(* com.health.ts.controller..*.*(..)) && !execution(* com.health.ts.controller.websocket..*.*(..))"
    		+ "&& !execution(* com.health.ts.controller.PageController.*(..)) ")
    public void excudeService() {
    }

    @Around("excudeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
//        HttpServletResponse response = sra.getResponse();

        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        Object result = null;
        if(isAjax(request)) {
            StopWatch watch = new StopWatch("ajax请求耗时统计");
            watch.start();
            result = pjp.proceed();
            watch.stop();
            log.debug("ajax请求,  uri: {}, method: {}, params: {}, cost: {}ms", uri, method, queryString, watch.getTotalTimeMillis());
            // result的值就是被拦截方法的返回值
//            JSONObject dd = JSONObject.parseObject(result.toString());
//            dd.put("traceId",tracer.currentSpan().context().traceIdString());
//            log.info("请求结束，controller的返回值是 {} - {}", tracer.currentSpan().toString(), dd.toJSONString());
//            response.setHeader("traceId", TLogContext.getTraceId());
        }else {
        	result = pjp.proceed();
        }
        return result;
    }
    
	/**
	 * 是否是Ajax请求
	 * 
	 * @param request
	 * @return
	 */
	private boolean isAjax(ServletRequest request) {
		return "XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"));
	}
}